<template>
  <div class="create-post-page">
    <Uploader :befor-upload="beforeUplad" @file-success="onFIleUpload" @file-error="onFIleUpload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :uploaded="uploadData">
      <template #default>
        <h2>点击上传图片</h2>
      </template>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <!-- <span class="sr-only">Loading...</span> -->
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #success="dataProps">
        <img :src="dataProps.uploadData.url">
        <!-- <h1>{{ dataProps.uploadData.url }}</h1> -->
      </template>
    </Uploader>
    <h4>{{ isEditMode ? '更新文章' : '新建文章' }}</h4>
    <ValidateFrom @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="from-label">文章标题：</label>
        <ValidateInput tag="input" :rules="titleRules" v-model="titleVal" placeholder="请输入文章标题" type="text" />
      </div>
      <div class="mb-3">
        <label class="from-label">文章内容：</label>
        <Editor v-model="contentVal" :options="editorOptions" ref="getEasymde" @blur="checkEditor"
          :class="{ 'is-invalid': !editorStatus.isValid }"></Editor>
        <span v-if="!editorStatus.isValid" class="invalid-feedback mt-1">{{ editorStatus.message }}</span>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '更新文章' : '创建文章' }}</button>
      </template>
    </ValidateFrom>
  </div>
</template>
<script setup lang="ts">
import Uploader from '../components/Uploader.vue';
import ValidateFrom from '../components/ValidateFrom.vue';
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { GlobalDataProps, PostProps, Avatar, ResponseType } from '../store/store';
import { onMounted, reactive, ref } from 'vue';
import createMessage from '../components/createMessage'
import { beforeUploadCheck } from '../helper';
import Easymde, { Options } from 'easymde';
import Editor from '../components/Editor.vue';

const uploadData = ref()
// 标题内容
let titleVal = ref('')
const stort = useStore<GlobalDataProps>()
const router = useRouter()
const route = useRoute()
// 验证规则
const titleRules: RulesProp = [
  { type: 'required', message: '文章标题不能为空' }
]
// 文章详细
let contentVal = ref('')

let imgId = ''
const handleFileUploader = (rawData: ResponseType<Avatar>) => {
  if (rawData.data._id) {
    imgId = rawData.data._id
  }
}
// 上传的回调
const onFormSubmit = (result: boolean) => {
  checkEditor()
  if (result && editorStatus.isValid) {
    const { _id, column, } = stort.state.user
    if (column) {
      const newPops: PostProps = {
        title: titleVal.value,
        content: contentVal.value,
        column,
        author: _id
      }
      if (imgId) {
        newPops.image = imgId
      }
      // 判断是否是更新 发送不同请求
      const actionName = isEditMode ? 'pathUpdataPosts' : 'CreatePosts'
      const sendData = isEditMode ? {
        id: route.query.id,
        payload: newPops
      } : { payload: newPops }
      stort.dispatch(actionName, sendData).then(() => {
        createMessage(`${isEditMode? '更新': '创建'}文章成功，两秒后跳转`, 'success')
        setTimeout(() => {
          router.push({ name: 'column', params: { id: column } })
        }, 2000);
      })
    }
  }
}
// 验证文件
const beforeUplad = (file: File) => {
  const { passed, error } = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
  if (error === 'format') {
    createMessage('文件格式错误, 只能为jpg / png', 'error')
  }
  if (error === 'size') {
    createMessage('文件大小错误', 'error')
  }
  return passed
}
// 图片上传成功失败的回调
const onFIleUpload = (rawData: ResponseType<Avatar>) => {
  if (rawData.msg === '请求成功') {
    createMessage('上传成功', 'success')
    handleFileUploader(rawData)
  } else {
    createMessage('上传失败', 'error')
  }
}

// 是否携带 query参数
const isEditMode = !!route.query.id
// 如果存在发送请求
onMounted(() => {
  // if (getEasymde.value) {
  //   console.log(getEasymde.value.getEasyMDEInstance());
  // }
  if (isEditMode) {
    stort.dispatch('getPostDetail', {id: route.query.id}).then((data: ResponseType<PostProps>) => {
      const currentPost = data.data
      if (currentPost.image) {
        uploadData.value = currentPost.image
      }
      titleVal.value = currentPost.title
      contentVal.value = currentPost.content || ''
    })
  } else {
    titleVal.value = ''
    contentVal.value = ''
  }
})
// console.log(titleVal);
// 创建easymde 的配置项
const editorOptions: Options = {
  // 拼写检查
  spellChecker: false
}
// 定义 组件向外暴露的类型
interface Easy {
  clearInnerValue: () => void,
  getEasyMDEInstance: () => Easymde | null
}
// 获取 Easymde实例
const getEasymde = ref<Easy>()
// 定义显示表单的验证
const editorStatus = reactive({
  isValid: true,
  message: ''
})
// 验证的回调函数
const checkEditor = () => {
  if (contentVal.value.trim() === '') {
    editorStatus.isValid = false
    editorStatus.message = '文章不能为空'
  } else {
    editorStatus.isValid = true
    editorStatus.message = ''
  }
}
</script>

<style>
.create-post-page .file-upload-container {
  height: 100px;
  cursor: pointer;
}

.create-post-page .file-upload-container img {
  /* width: 100%; */
  height: 100%;
  object-fit: cover;
}
</style>